package com.rpframework.website.device.act.admin;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.rpframework.module.adminbase.domain.AdminUser;
import com.rpframework.utils.NumberUtils;
import com.rpframework.utils.Pager;
import com.rpframework.website.device.domain.Goods;
import com.rpframework.website.device.domain.GoodsStock;
import com.rpframework.website.device.domain.GoodsStockRecord;
import com.rpframework.website.device.service.GoodsService;
import com.rpframework.website.device.service.GoodsStockRecordService;
import com.rpframework.website.device.service.GoodsStockService;
import com.rpframework.website.device.util.HConstants;

/**
 * 出入库记录
 * @author zhangli
 * @date 2016年4月1日 上午10:32:39
 */
@Controller
@RequestMapping("/admin/record")
public class AdminGoodsStockRecordAct extends AdminAct{
	@Resource GoodsStockRecordService service;
	@Resource GoodsStockService stockService;
	@Resource GoodsService goodsService;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/list")
	public String list(@RequestParam(value="pager", required=false) Pager pager, 
			@RequestParam(value="state", required=false) Integer state, 
			@RequestParam(value="goodsId", required=false) Integer goodsId, 
			@RequestParam(value="relativeId", required=false) Integer relativeId, 
			HttpSession session,
			Map<Object, Object> model){
		if(pager == null) {
			pager = new Pager();
		}
		AdminUser t = (AdminUser) session.getAttribute(SESSION_ADMIN_USER_KEY);
		//relativeId 为0就是平台的库存 其它对应各个物业的库存
		if(t.getAdminRole().getIsSuper() != 1){
			pager.getSearchMap().put("relativeId", t.getRelativeId().toString());
		}else if(relativeId != null) {
			pager.getSearchMap().put("relativeId", relativeId.toString());
		}
		if(NumberUtils.isValid(goodsId)){
			pager.getSearchMap().put("goodsId", goodsId.toString());
			model.put("goodsId", goodsId.toString());
		}
		model.put("relativeId", t.getRelativeId().toString());
		model.put("adminRole", t.getAdminRole().getIsSuper());
		if(NumberUtils.isValid(state)){
			pager.getSearchMap().put("state", state.toString());
			model.put("state", state);
		}
		pager = service.getPager(pager);
		model.put("pager", pager);
		return this.doPackageURI("goods_record/list");
	}
	
	@RequestMapping("/submit")
	public String submit(@RequestParam(value="id", required=false) Integer id,
			RedirectAttributes attr){
		//将此记录的数量 加入库存
		if(NumberUtils.isNotValid(id)){
			throw new IllegalArgumentException("无效的id!");
		}
		GoodsStockRecord t = service.select(id);
		if(t == null)throw new IllegalArgumentException("无效的配送记录!");
		Goods goods = goodsService.select(t.getGoodsId());
		if(goods == null)throw new IllegalArgumentException("无效的商品!");
		GoodsStock dbUtils = stockService.searchStock(goods.getId(),t.getRelativeId());//原来有这件商品是否入库过  平台没有确认的功能
		boolean flag = false;
		if(dbUtils==null){
			dbUtils = new GoodsStock();
			dbUtils.setAmount(t.getAmount());
			dbUtils.setGoodsId(goods.getId());
			dbUtils.setGoodsName(goods.getName());
			dbUtils.setGoodsOldPrice(goods.getOldPrice());
			dbUtils.setGoodsDisPrice(goods.getDisPrice());
			dbUtils.setGoodsUrlList(goods.getUrlList());
			dbUtils.setGoodsPoint(goods.getPoint());
			dbUtils.setCreateTime(System.currentTimeMillis() / 1000);
			dbUtils.setState(HConstants.EntityState.STATE_NORMAL);
			dbUtils.setRelativeId(t.getRelativeId());//后台管理员登录管理的小区id 
			flag = stockService.insert(dbUtils);
		}else{
			 dbUtils.setGoodsName(goods.getName());
			 dbUtils.setGoodsOldPrice(goods.getOldPrice());
			 dbUtils.setGoodsDisPrice(goods.getDisPrice());
			 dbUtils.setGoodsUrlList(goods.getUrlList());
			 dbUtils.setModifyTime(System.currentTimeMillis() / 1000);
			 dbUtils.setState(HConstants.EntityState.STATE_NORMAL);
			 dbUtils.setAmount(dbUtils.getAmount()+t.getAmount());
			 if(t.getStatus() == 2){//用户买走的，不加到物业库存.且这条记录不能被修改.如果平台又重新配送了单子，物业的库存会加上。
				 dbUtils.setAmount(dbUtils.getAmount()+0); 
				 //物业公司确认这条由用户需求而生成的配送单时是不加库存的。如果平台不只配送了差量，还额外配送了。那就是平台配送的数量-用户购买的差量 作为最终库存
				 //平台可能改这条固定配送的数量，可能多加一条配送的记录，而小区确认的顺序是随机确认的
			 }
			 dbUtils.setRelativeId(t.getRelativeId());//后台管理员登录管理的物业id 0是超级管理员
			 flag = stockService.update(dbUtils);
		}
		if(flag){
			t.setState(HConstants.EntityState.STATE_NORMAL);//确认成功
			boolean f1 = service.update(t);
			if(f1)setInfoMsg("确认配送成功！", attr);
		}
		//更改此记录状态为已配送成功
		return redirect("/admin/record/list");
	}
	@RequestMapping("/delete-{id}")
	public String delete(@PathVariable Integer id ,
			RedirectAttributes attr){
		GoodsStockRecord t = service.select(id);
		if(t!=null){
			GoodsStock gs = stockService.searchStock(t.getGoodsId(), 0);//还回平台库存
			gs.setAmount(gs.getAmount()+t.getAmount());
			gs.setModifyTime(System.currentTimeMillis()/1000);
			stockService.update(gs);
		}
		boolean flag = service.delete(id);
		if(flag){
			setInfoMsg("删除成功！", attr);
		}else{
			setInfoMsg("删除失败！", attr);
		}
		return redirect("/admin/record/list");
	}
	
	@RequestMapping("/edit-{id}")
	public String edit(@PathVariable Integer id, Map<Object, Object> model,RedirectAttributes attr){
		GoodsStockRecord t = service.select(id);
		Assert.notNull(t,this.getClass().getName() + " Id 异常");
		model.put("pager", t);
		return this.add(attr, model,t.getGoodsId(),t.getRelativeId(),t.getAmount());
	}
	@RequestMapping("/add")
	public String add(RedirectAttributes attr,Map<Object, Object> model,
			@RequestParam(value="goodsId", required=false) Integer goodsId,
			@RequestParam(value="relativeId", required=false) Integer relativeId,
			@RequestParam(value="amount", required=false) Double amount
			){
		if(NumberUtils.isValid(goodsId)){
				model.put("goodsId", goodsId);
		}
		if(NumberUtils.isValid(relativeId)){
			model.put("relativeId", relativeId);
		}
		if(NumberUtils.isValid(amount)){
			model.put("amount", amount);
		}
		return this.doPackageURI("goods_record/edit");
	}
	@RequestMapping("/add2")
	public String add2(RedirectAttributes attr,Map<Object, Object> model
			){
		return this.doPackageURI("goods_record/edit");
	}
	@RequestMapping("/dosave")
	public String doSaveOrUpdate(@ModelAttribute GoodsStockRecord t,
			RedirectAttributes attr){
		boolean flag = false;
		flag = service.doSaveOrUpdate(t);
		if(flag){
			if(NumberUtils.isValid(t.getId())) {
				setInfoMsg("更新操作成功！", attr);
			} else {
				setInfoMsg("新增操作成功！", attr);
			}
		}else{
			setInfoMsg("操作失败！平台库存不足！", attr);
		}
		return redirect("/admin/record/list");
	}
	
	
}
